<template>
	<div>
		<div class="container">
			<div class="handle-box">
                <!--搜索条件：一个输入框（歌手/歌名/介绍）-->
                <!--列表显示 歌手、歌名、介绍、图片、url-->
            <div class="handle-box">
              
                <el-input v-model="query.name" placeholder="歌手/歌名/介绍" class="handle-input mr10"></el-input>
                <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
                <el-button type="primary" :icon="Plus" @click="handleAdd">新增</el-button>
            </div>
            <!--列表展示数据区域:歌手、歌名、介绍、图片、url、操作按钮-->
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header">
				<el-table-column type="index" label="序号" width="55" align="center"></el-table-column>
				<el-table-column prop="singerName" label="歌手"></el-table-column>
				<el-table-column prop="name" label="歌名"></el-table-column>
				<el-table-column prop="introduction" label="介绍"></el-table-column>
				<el-table-column label="图片" align="center">
					<template #default="scope">
						<el-image
							class="table-td-thumb"
							:src="getImageUrl(scope.row.pic)"
							:z-index="10"
							:preview-src-list="[getImageUrl(scope.row.pic)]"
							preview-teleported
						>
						</el-image>
					</template>
				</el-table-column>
				
				<el-table-column label="操作" width="220" align="center">
					<template #default="scope">
						 <el-button text :icon="Edit" @click="handleEdit(scope.$index, scope.row)" v-permiss="15">
							编辑
						</el-button>
						<el-button text :icon="Delete" class="red" @click="handleDelete(scope.row)" v-permiss="16">
							删除
						</el-button> 
					</template>
				</el-table-column>
			</el-table>
            <!--分页导航条-->
            <div class="pagination">
				<el-pagination
					background
					layout="total, prev, pager, next"
					:current-page="query.pageNum"
					:page-size="query.pageSize"
					:total="pageTotal"
					@current-change="handlePageChange"
				></el-pagination>
			</div>
			</div>
			<!-- 编辑弹出框，通过 editVisible 控制是否显示，在用户点击“新增”、“编辑”按钮时打开。 -->
		    <!-- 歌手singerId、歌名name、介绍introduction、图片pic、url -->
			<el-dialog title="编辑" v-model="editVisible" width="80%">
			<el-form label-width="70px">
				<!-- 需要添加、修改的内容绑定在 from 对象中，添加、修改时同时提交至后端接口 -->
				<el-form-item label="歌曲名称">
					<el-input v-model="form.name"></el-input>
				</el-form-item>
				<el-form-item label="歌手">
					<!-- <el-input v-model="form.singerId"></el-input> -->
					<el-select
                      v-model="form.singerId"
                      filterable remote placeholder="请输入歌名...."
                      :remote-method="remoteMethod"
                      :loading="loading"
                      style="width: 240px"
                     >
                      <el-option
                        v-for="singer in singers"
                        :key="singer.id"
                        :label="singer.name"
                        :value="singer.id"
                        />
                        </el-select>
				</el-form-item>
				<el-form-item label="介绍">
					<el-input v-model="form.introduction" type="textarea" :rows="5"></el-input>
				</el-form-item>
				<el-form-item label="图片">
					<el-upload style="display: display;"
						class="avatar-uploader"
						:action="serverUrl + '/upload/image'"
						:show-file-list="false"
						:on-success="handleAvatarSuccess"
						:before-upload="beforeAvatarUpload"
						>
						<img v-if="form.pic" :src="getImageUrl(form.pic)" class="avatar" />
    					<el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="歌词">
					<el-input v-model="form.lyric" type="textarea" :rows="5"></el-input>
				</el-form-item>
				<el-form-item label="歌曲文件">
				</el-form-item>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="editVisible = false">取 消</el-button>
					<!-- 点击“确定”按钮触发 saveEdit 函数，在该函数中实现添加、修改业务。 -->
					<el-button type="primary" @click="saveEdit">确 定</el-button>
				</span>
			</template>
			
		</el-dialog>
		</div>
    </div>	
</template>
<script setup lang="ts">
import {reactive, ref} from 'vue'
import {Delete, Edit, Search, Plus} from '@element-plus/icons-vue';
import http from '../utils/request';
import { serverUrl } from '../utils/request';
import type { UploadProps } from 'element-plus'
import { ElMessage, ElMessageBox, formItemValidateStates } from 'element-plus';
import { getImageUrl } from '../utils/index';
//总记录数
const pageTotal = ref(0);

//搜索表单对象
//总记录数，渲染分页导航条
const query = reactive({
    name: '',
    pageNum:1,
    pageSize:10,
});
//渲染列表数据源
const tableData = ref([]);

const getData = async function(){
    console.log('getData....')
    // const res = await fetch('https://yesno.wtf/api')
    // console.log(await res);
   // http.get('admin/song?pageNum= ' + query.pageNum + '&pageSize=' + query.pageSize + '&name' + query.name, {
	http.get('admin/song', {
		params: query
    }).then((res) => {
        console.log("【成功】获取歌曲列表:",res);
        //1.将查询到的列表数据赋值给 tableData
        tableData.value = res.data.data.list;
        console.log('tableData = ',tableData)
        //2.构造分页对象，展示分页导航条
        pageTotal.value = res.data.data.total;
    }).catch(error => {
        console.log("【失败】获取歌曲列表:",error);
    });
}
//点击"搜索"按钮触发
const handleSearch = function(){
    query.pageNum = 1;//设置页码为第1页
    getData();
}
//当用户点击分页导航条时触发
const handlePageChange = function(value: number){
    console.log('当前页面已改变,新页码 = ' ,value)
    query.pageNum = value;
    getData();
}
//进入页面之后自动调用getData查询并渲染数据
getData();

// 表格编辑时弹窗和保存
const editVisible = ref(false);
const form = reactive({
	id:0,
	singerId:null,  //歌手id
	name:'', //歌名
	introduction:'',//介绍
	pic:'', //头像
	lyric:'',//歌词
	url:'', //歌曲文件
})

//上传文件前回调该方法，用于校验文件格式、大小；
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  console.log('beforeAvatarUpload = ', rawFile);
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('上传图片必须是JPG类型')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('图片大小不能超过2M!')
    return false
  }
  return true
}

//上传成功：会请求 action 属性配置的URL，成功后回调该方法；
const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
	//这里
  console.log('handleAvatarSuccess = ', response, ' uploadFile = ',uploadFile);
  if("200" === response.code){
	// form.pic = URL.createObjectURL(uploadFile.raw!)
	form.pic = response.url;//成功后将服务器返回的 url 赋值给 form.pic
  }
}
//保存
const handleAdd = () => {
	form.id = 0;
	form.singerId = null;
	form.name = '';
	form.pic = '';
	form.introduction = '';
	form.lyric = '';
	form.url = '';
	editVisible.value = true;
};
const saveEdit = () => {
	// ElMessage.success(`修改第 ${idx + 1} 行成功`);
	// tableData.value[idx].name = form.name;
	// tableData.value[idx].address = form.address;
	if(!form.id){	//form.id 为空：新增
		console.log('新增', form);
		http.post("/admin/song", form)
		.then((res) => {
			console.log('新增返回值：', res);
			if(res.data.code === 200){	//新增成功
				ElMessage.success(`新增成功`);
				editVisible.value = false;
				getData();
			}
		}).catch((err) => {
			console.log('新增失败：', err);
			ElMessage.error(`新增失败`);
		});
	}else{ //修改
		console.log('修改', form);
		http.put("/admin/song", form)
		.then((res) => {
			console.log('修改返回值：', res);
			if(res.data.code === 200){	//修改成功
				ElMessage.success(`修改成功`);
				editVisible.value = false;
				getData();
			}
		}).catch((err) => {
			console.log('修改失败：', err);
			ElMessage.error(`修改失败`);
		});
	}
};
const handleEdit = function(index:number,row:any){
	//如果需要查询记录详细信息，则调用根据ID获取详情接口，将获取到的内容赋值给form对象
	editVisible.value = true;
	form.id = row.id;
	form.introduction = row.introduction;
	form.lyric = row.lyric;
	form.name = row.name;
	form.pic = row.pic;
	form.singerId = row.singerId;
	form.url = row.url;
}
//实现歌曲的删除
const handleDelete = function(row: any){
	ElMessageBox.confirm(
    `确定要删除歌曲【${row.name}】吗？`,'提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      http.delete('/admin/song/' + row.id)
	  .then((res) => {
		if(res.data.code === 200){
			ElMessage.success("删除成功!")
			handleSearch();
		}
    }).catch((err) => {
      console.log("删除失败：",err);
	  ElMessage.error('删除失败！')
      });
    }).catch(() =>{

	})
}

//实现歌手搜索填充
interface Singer {
  id: number
  name: string
}
const loading = ref(false)
const singers = ref<Singer[]>([])
const remoteMethod = (keyword: string) => {
  if (keyword) {
    loading.value = true
   //请求根据关键字模糊搜索歌手列表接口，获取歌手数据
   http.get("admin/singer/top30",{
	params:{ keyword },
   }).then((res) =>{
	    console.log('查询的歌手列表是：',res.data);
		singers.value = res.data.data;
   }).catch((err)=>{

   })
   loading.value = false;
  } else {
    singers.value = []
  }
}


</script>
<style scoped>
.handle-box {
	margin-bottom: 20px;
}

.handle-select {
	width: 120px;
}

.handle-input {
	width: 300px;
}
.table {
	width: 100%;
	font-size: 14px;
}
.red {
	color: #ff0000;
}
.mr10 {
	margin-right: 10px;
}
.table-td-thumb {
	display: block;
	margin: auto;
	width: 40px;
	height: 40px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>